<?php
declare(strict_types=1);

namespace app\controller\merchant;

use app\controller\BaseController;
use app\model\{Merchant, MerchantApplication};
use think\exception\ValidateException;
use think\facade\{Cache, Validate, Db, Queue};
use app\job\IpLocationJob;

class AuthController extends BaseController
{
    /**
     * 商家登录
     */
    public function login()
    {
        $params = $this->request->post();
        
        try {
            validate([
                'username|用户名' => 'require',
                'password|密码' => 'require'
            ])->check($params);
            
            $merchant = Merchant::where('contact_phone', $params['username'])->find();
            if (!$merchant || !password_verify($params['password'], $merchant->password)) {
                return $this->error('用户名或密码错误');
            }
            
            if (!$merchant->isAvailable()) {
                return $this->error('账号已被禁用');
            }
            
            // 生成token
            $token = $this->createToken($merchant->id);
            
            return $this->success([
                'token' => $token,
                'merchant' => [
                    'id' => $merchant->id,
                    'merchant_name' => $merchant->merchant_name,
                    'contact_name' => $merchant->contact_name,
                    'contact_phone' => $merchant->contact_phone
                ]
            ]);
            
        } catch (ValidateException $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 修改密码
     */
    public function changePassword()
    {
        $params = $this->request->post();
        $merchant = $this->request->merchant;
        
        try {
            validate([
                'old_password|原密码' => 'require',
                'new_password|新密码' => 'require|min:6',
                'confirm_password|确认密码' => 'require|confirm:new_password'
            ])->check($params);
            
            if (!password_verify($params['old_password'], $merchant->password)) {
                return $this->error('原密码错误');
            }
            
            $merchant->password = password_hash($params['new_password'], PASSWORD_DEFAULT);
            if (!$merchant->save()) {
                return $this->error('修改失败');
            }
            
            return $this->success();
            
        } catch (ValidateException $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 获取商家信息
     */
    public function info()
    {
        $merchant = $this->request->merchant;
        
        return $this->success([
            'id' => $merchant->id,
            'merchant_name' => $merchant->merchant_name,
            'merchant_type' => $merchant->merchant_type,
            'merchant_type_text' => $merchant->getTypeTextAttr(),
            'contact_name' => $merchant->contact_name,
            'contact_phone' => $merchant->contact_phone,
            'email' => $merchant->email,
            'balance' => $merchant->balance
        ]);
    }

    /**
     * 修改商家信息
     */
    public function updateInfo()
    {
        $params = $this->request->post();
        $merchant = $this->request->merchant;
        
        try {
            validate([
                'merchant_name|商家名称' => 'require|max:50',
                'contact_name|联系人' => 'require|max:20',
                'contact_phone|联系电话' => 'require|mobile',
                'email|邮箱' => 'email'
            ])->check($params);
            
            $merchant->merchant_name = $params['merchant_name'];
            $merchant->contact_name = $params['contact_name'];
            $merchant->contact_phone = $params['contact_phone'];
            $merchant->email = $params['email'] ?? '';
            
            if (!$merchant->save()) {
                return $this->error('修改失败');
            }
            
            return $this->success();
            
        } catch (ValidateException $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 记录登录日志
     */
    protected function recordLoginLog($merchantId, $ip, $type, $content)
    {
        // 记录登录日志
        $logId = Db::name('merchant_login_log')->insertGetId([
            'merchant_id' => $merchantId,
            'ip' => $ip,
            'type' => $type,
            'content' => $content,
            'create_time' => date('Y-m-d H:i:s')
        ]);
        
        // 异步查询IP地理位置
        Queue::push(IpLocationJob::class, [
            'type' => 'merchant',
            'log_id' => $logId,
            'ip' => $ip
        ]);
    }
} 